package org.yufan.core.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.yufan.core.result.Result;
import org.yufan.core.result.ResultUtils;
import org.yufan.core.result.StatusCode;
import org.yufan.core.utils.JsonUtils;
import org.yufan.core.utils.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Created by zxd on 2019/3/1
 **/
public class CustomerExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {

        String msg;

        if(exception instanceof CustomerException){
            msg=exception.getMessage();
        }else{
            exception.printStackTrace();
            msg="对不起，系统开小差了!";
        }

        HandlerMethod handlerMethod= (HandlerMethod) handler;
        //获取处理器方法
        Method method = handlerMethod.getMethod();

        Class controllerClazz=handlerMethod.getBean().getClass();
        //1.判断controller类上面有没有ResponseBody注解
        //2.类上面没有，判断方法上面有没有ResponseBody注解或者返回值类型为ResponseEntity
        ResponseBody responseBody = (ResponseBody) controllerClazz.getAnnotation(ResponseBody.class);
        if(responseBody==null){
            //类上面没有 方法上面找
            responseBody=method.getAnnotation(ResponseBody.class);
        }

        ModelAndView modelAndView=new ModelAndView();

        if(responseBody!=null||method.getReturnType().getName().equals(ResponseEntity.class.getName())){
            //返回json数据
            Result result = ResultUtils.buildFail(50000, msg);
            ResponseUtils.responseJson(response,JsonUtils.objectToJson(result));
           return modelAndView;
        }
        modelAndView.setViewName("error");
        modelAndView.addObject("msg",msg);
        return modelAndView;
    }
}
